package cn.tedu.loginsaltweb.service;

import cn.tedu.loginsaltweb.exception.ServiceException;
import cn.tedu.loginsaltweb.mapper.UserMapper;
import cn.tedu.loginsaltweb.pojo.dto.UserDTO;
import cn.tedu.loginsaltweb.pojo.entity.User;
import cn.tedu.loginsaltweb.pojo.vo.UserVO;
import cn.tedu.loginsaltweb.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements IUserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPasswordHash(); // 实际上是明文密码
        log.debug("开始处理注册功能，参数：{}", userDTO);

        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO != null) {
            throw new ServiceException(StatusCode.OPERATION_FAIL); // 用户名已存在
        }

        // 推荐：用 Spring 封装好的方式加密密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String hashedPassword = encoder.encode(password); // 安全加密

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setPasswordHash(hashedPassword);

        int res = userMapper.insert(user);
        log.info("用户注册成功，受影响的行数：{}", res);
    }

    @Override
    public Boolean login(UserDTO userDTO) {
        String passwordInput = userDTO.getPasswordHash(); // 实际是用户输入的密码
        String username = userDTO.getUsername();
        log.debug("用户登录UsrDTO{}" + userDTO);

        // 1. 查用户
        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO == null) {
            throw new ServiceException(StatusCode.OPERATION_FAIL); // 用户不存在
        }

        // 2. 拿出数据库的密码哈希
        String storedHash = userVO.getPasswordHash();

        // 3. 用 BCryptPasswordEncoder 验证密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(passwordInput, storedHash)) {
            throw new ServiceException(StatusCode.OPERATION_FAIL); // 密码不正确
        }

        return true; // 登录成功
    }

}
